package com.anhry.www.safety.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Random;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 2010-04-08
 * remark: 文件上传
 * author: anhry
 *
 */
public class UploadFile {
	private static final int BUFFER_SIZE = 16 * 1024;
    /**
     * 参数说明
     * @param src 上传文件时的file名称
     * @param dst 文件要存放的路径
     * @param fileName 文件名称
     * @param id 要具体存放的路径
     * @return
     */
	public static String copy(File src, String dst,String fileName, String id) {
		InputStream in = null;
		OutputStream out = null;
		//String dirpath = dst;
		//文件存储路径
		if (id != null && !"".equals(id)) {
			dst = dst + "/" + id +"/";
		}
		//String fileRealPath = dst;// 文件所存的地址
		Random r = new Random();
		String file_type = fileName.substring(fileName.lastIndexOf(".") + 1);
		String file_name = Calendar.getInstance().getTimeInMillis()
				+ r.nextInt(100) + "." + file_type;
		File realDir = new File(dst);
		// 判断文件夹是否存在
		// boolean dirflag = dir.exists();
		boolean realdirflag = realDir.exists();

		// if (!dirflag) {
		// // 不存在先创建,然后再创建子文件夹
		// dir.mkdir();
		// }
		if (!realdirflag) {
			realDir.mkdirs();
		}
		// 显示相应文件夹下的所有文件
		String[] list = realDir.list();
		// 此循环控制是否插入重复的资料
		if (list != null) {
			for (int i = 0; i < list.length; i++) {
				if (fileName.equals(list[i])) {
					return "";
				}
			}
		}
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst + "/" + file_name),BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		//String files = fileRealPath + File.separator + file_name;
//		UploadFile.zipImageFile(files.replaceAll("\\\\", "/"), 0, 0, 1f, null);
		return file_name;
	}
	/**
	 * 参数说明
	 * @param src 上传文件时的file名称
	 * @param dst 文件要存放的路径
	 * @param fileName 文件名称
	 * @return
	 */
	public static String copy2(File src, String dst,String fileName) {
		InputStream in = null;
		OutputStream out = null;
		String dirpath = dst;
		String fileRealPath = dirpath;// 文件所存的地址
		Random r = new Random();
		String file_type = fileName.substring(fileName.lastIndexOf(".") + 1);
		String file_name = Calendar.getInstance().getTimeInMillis()
		+ r.nextInt(100) + "." + file_type;
		File realDir = new File(dirpath);
		// 判断文件夹是否存在
		// boolean dirflag = dir.exists();
		boolean realdirflag = realDir.exists();
		
		// if (!dirflag) {
		// // 不存在先创建,然后再创建子文件夹
		// dir.mkdir();
		// }
		if (!realdirflag) {
			realDir.mkdirs();
		}
		// 显示相应文件夹下的所有文件
		String[] list = realDir.list();
		// 此循环控制是否插入重复的资料
		if (list != null) {
			for (int i = 0; i < list.length; i++) {
				if (fileName.equals(list[i])) {
					return "";
				}
			}
		}
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(fileRealPath + File.separator + file_name),BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
//			UploadFile.zipImageFile(files.replaceAll("\\\\", "/"), 0, 0, 1f, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return file_name;
	}
	public static boolean thumImage(String file_pathS, String file_pathR,
			String file_name) {
		try {
			String image_path = file_pathR;
			File dir = new File(image_path);
			if (!dir.exists()) {
				// 不存在先创建,然后再创建子文件夹
				dir.mkdir();
			}
			String tem_path = file_pathS;
			BufferedImage imageS = ImageTools.readImage(tem_path+ File.separator + file_name);
			BufferedImage imageR = ImageTools.thumbFilter(imageS, 800,600);
			ImageTools.writeImage(imageR, image_path + File.separator + file_name);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
    public static String zipImageFile(String oldFile, int width, int height,   
            float quality, String smallIcon) {   
        if (oldFile == null) {   
            return null;   
        }   
        String newImage = null;   
        try {   
            /** 对服务器上的临时文件进行处理 */  
            Image srcFile = ImageIO.read(new File(oldFile));
            int w = srcFile.getWidth(null);//原来宽度
            int h = srcFile.getHeight(null);//原来高度
            width = w;
            height = h;
            int tem = (w*h)/(800*600);
            if(tem>1){
            	if(w>h){//如果原来图片宽大于高
            		width = w/(w/800);
            		height = h/(w/800);
            	}else{
            		width = w/(h/800);
            		height = h/(h/800);
            	}
            }
            System.out.println(width);
            System.out.println(height);
            //width = w/4;
            //height = h/4;
            
            /** 宽,高设定 */  
            BufferedImage tag = new BufferedImage(width, height,   
                    BufferedImage.TYPE_INT_RGB);   
            tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);   
            String filePrex = oldFile.substring(0, oldFile.indexOf('.'));   
            /** 压缩后的文件名 */  
            newImage = filePrex   
                    + oldFile.substring(filePrex.length());   
            
  
            /** 压缩之后临时存放位置 */  
            FileOutputStream out = new FileOutputStream(newImage);   
  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);   
            /** 压缩质量 */  
            jep.setQuality(quality, true);   
            encoder.encode(tag, jep);   
            out.close();   
  
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        return newImage;   
    }

	// 删除文件:
	public static void removeFile(String path) {
		removeFile(new File(path));
	}

	public static void removeFile(File path) {
		if(path.exists()){
			if (path.isDirectory()) {
				File[] child = path.listFiles();
				if (child != null && child.length != 0) {
					for (int i = 0; i < child.length; i++) {
						removeFile(child[i]);
						child[i].delete();
					}
				}
			}
			path.delete();
		}else{
			Loggers.info("你所删除的文件不存在");
		}
	}
	
	/**
	 * 判断文件是否存在
	 * @param path
	 * @return
	 */
	public static boolean fileExist(String path){
		java.io.File file = new java.io.File(path);       
		if(file.exists()){       
			return true;    
		}else{       
			return false;       
		}       
	}
}
